import React, { useState, useRef, useEffect } from 'react';
import { Button, List, Tag } from 'antd';

// 父组件：支持打开多个子窗口并分别通信
const OpenMultipleCommunicatingTabs = () => {
  const [windowMap, setWindowMap] = useState(new Map()); // 存储窗口实例和ID
  const [windowList, setWindowList] = useState([]); // 用于展示窗口列表
  const nextWindowId = useRef(1); // 窗口ID生成器

  // 打开新的子窗口
  const openNewTab = () => {
    const windowId = nextWindowId.current++;
    // const newWindow = window.open('/communicate-tab', '_blank');
    const newWindow = window.open('http://localhost:3001/#/admin/communicate-tab-multi', '_blank');

    
    if (newWindow) {
      // 存储窗口实例和ID
      setWindowMap(prevMap => {
        const newMap = new Map(prevMap);
        newMap.set(windowId, { window: newWindow, active: true });
        return newMap;
      });
      
      // 更新窗口列表
      setWindowList(prevList => [
        ...prevList,
        { id: windowId, status: 'active', created: new Date() }
      ]);
      
      // 发送初始化数据（携带窗口ID）
      newWindow.postMessage(
        { 
          type: 'INIT_DATA', 
          data: { 
            message: `来自父窗口的初始化数据 (窗口ID: ${windowId})`,
            windowId
          } 
        },
        '*'
      );
    }
  };

  // 向指定窗口发送消息
  const sendToWindow = (windowId, message) => {
    const windowEntry = windowMap.get(windowId);
    if (windowEntry && windowEntry.active && windowEntry.window) {
      windowEntry.window.postMessage(
        { 
          type: 'PARENT_COMMAND', 
          data: { 
            command: message,
            windowId
          } 
        },
        '*'
      );
    }
  };

  // 接收子窗口消息
  useEffect(() => {
    const handleMessage = (e) => {
      const { type, data } = e.data;
      const { windowId } = data || {};
      
      if (type === 'CHILD_RESPONSE' && windowId !== undefined) {
        console.log(`子窗口 ${windowId} 响应:`, data.payload);
        
        // 更新窗口状态
        setWindowMap(prevMap => {
          const newMap = new Map(prevMap);
          const windowEntry = newMap.get(windowId);
          if (windowEntry) {
            newMap.set(windowId, {
              ...windowEntry,
              lastMessage: new Date()
            });
          }
          return newMap;
        });
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [windowMap]);

  // 检测窗口是否关闭
  useEffect(() => {
    const checkWindows = () => {
      setWindowMap(prevMap => {
        const newMap = new Map(prevMap);
        newMap.forEach((entry, id) => {
          if (entry.window && entry.window.closed) {
            newMap.set(id, { ...entry, active: false });
          }
        });
        return newMap;
      });
    };

    // 定期检查窗口状态
    const interval = setInterval(checkWindows, 1000);
    return () => clearInterval(interval);
  }, [windowMap]);

  return (
    <div>
      <h3>多子窗口通信演示</h3>
      <Button type="primary" onClick={openNewTab}>
        打开新的子标签页
      </Button>
      
      <div style={{ marginTop: 20 }}>
        <h4>已打开的子窗口列表</h4>
        <List
          itemLayout="horizontal"
          dataSource={windowList}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                title={`窗口 ID: ${item.id}`}
                description={`创建时间: ${item.created.toLocaleString()}`}
              />
              <Button 
                size="small" 
                onClick={() => sendToWindow(item.id, 'refreshData')}
              >
                发送刷新命令
              </Button>
              <Tag color={item.status === 'active' ? 'success' : 'default'}>
                {item.status}
              </Tag>
            </List.Item>
          )}
        />
      </div>
    </div>
  );
};
export default OpenMultipleCommunicatingTabs;
